<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="list-box">
    <div class="list-header">
      <el-icon class="back-btn" style="margin-right: 10px" @click="() => back()"><ArrowLeft /></el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>业务分组</el-breadcrumb-item>
        <el-breadcrumb-item>领域知识</el-breadcrumb-item>
        <el-breadcrumb-item>Key</el-breadcrumb-item>
        <el-breadcrumb-item>Value</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="list-content">
      <if-filter-items :form="state.form" :fields="state.fields" @change="updateFilter"></if-filter-items>
      <div style="display: flex; align-items: center; justify-content: flex-end; margin-bottom: 12px;">
        <el-button type="primary" style="border-radius: 4px" @click="goAddAssets('BIZ_NODE')">新增Value</el-button>
      </div>
      <ifTable :list="state.listData" :columns="columns" :pageModel="state.pageModel" :loading="state.loading"
        @search="changePage" :border="false">
        <el-table-column v-if="isIndex" label="序号" type="index" align="center" width="65px">
        </el-table-column>
        <template v-slot:label="{ scopeData }">
          <p v-for='(item, index) in scopeData.row.label' :key='index'>{{item}}</p>
        </template>
        <template v-slot:createTime="{ scopeData }">
          <p>{{scopeData.row?.createTime?.substring(0, 10)}}</p>
          <p>{{scopeData.row?.createTime?.substring(10)}}</p>
        </template>
        <template v-slot:updateTime="{ scopeData }">
          <p>{{scopeData.row?.updateTime?.substring(0, 10)}}</p>
          <p>{{scopeData.row?.updateTime?.substring(10)}}</p>
        </template>
        <!-- businessManagers -->
        <template v-slot:action="{ scopeData }">
          <el-link class="action-btn" @click="() => handleEdit(scopeData.row, scopeData.rowIndex)" type="success">编辑</el-link>
          <el-link class="action-btn" @click="() => handleAddLabels(scopeData.row, scopeData.rowIndex)" type="success">添加标签</el-link>
          <el-popconfirm
          confirm-button-text="确定"
          cancel-button-text="取消"
          title="您确定要删除吗？"
          @confirm="handleRemove(scopeData.row, scopeData.rowIndex)"
          >
            <template #reference>
              <el-link type="danger">删除</el-link>
            </template>
          </el-popconfirm>
        </template>
      </ifTable>
    </div>
    <DetailDialog v-if="dialogVisible" :dialogVisible="dialogVisible" :dialogData="dialogData" @changeVisible="changeVisible" @sendDataToParCom="sendDataToParCom" />
    <addLabels v-if="labelDialog" :dialogVisible="labelDialog" @changeVisible="changeLabelVisible"  @sendDataToParCom="sendDataToParComLabel" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { columns, filterForm } from './config'
import { assetsManage } from '@/services/assets'
import { debounce } from '@/utils/utils'
import DetailDialog from './components/detail.vue'
import addLabels from './components/addLabels.vue'
import IfFilterItems from '@/components/if-filter-items/index.vue'
import ifTable from '@/components/if-table/if-table.vue'

const router = useRouter()
const route = useRoute()

const state = reactive<any>({
  filterData: {},
  listData: [],
  loading: false,
  form: {},
  fields: ref(filterForm),
  pageModel: {
    currentPage: 1,
    pageSize: 10,
    totalCount: 0,
    layout: 'total, sizes, prev, pager, next, jumper'
  },
})

const nodeId = ref('')
const isIndex = ref<boolean>(true)
const dialogVisible = ref<boolean>(false)
const labelDialog = ref<boolean>(false)
const dialogData = ref<Record<string, any>>()

const back = () => {
  router.go(-1)
}
const changeVisible = (flag: any) => {
  dialogVisible.value = flag
}
const changeLabelVisible = (flag: any) => {
  labelDialog.value = flag
}
const changePage = debounce((data: any) => {
  state.pageModel = { ...state.pageModel, ...data }
  loadData()
}, 500, true)

const loadData = debounce(async () => {
  state.loading = true
  try {
    const params = {
      id: nodeId.value,
      pageSize: state.pageModel.pageSize,
      pageNum: state.pageModel.currentPage,
    }
    const res = await assetsManage.getNodeByNodeTypeAndId(params)
    const { code, data } = res
    if (code === '000000') {
      state.listData = data.content
      state.pageModel.totalCount = Number(data.total)
      isIndex.value = computed(() => {
        return data?.content.some((item: any) => item.type === 'index')
      })
    }
  } catch (e) {
    state.loading = false
    state.listData = []
    isIndex.value = true
    console.log(e)
  } finally {
    state.loading = false
  }
}, 500, true)

const updateFilter = (filter: any) => {
  if (!filter.isTrusted) {
    state.pageModel.currentPage = 1
    state.filterData = { ...filter }
    loadData()
  }
}

const goAddAssets = (type: string) => {
  router.push({ path: '/valnode/add', query: { type, id: nodeId.value } })
}

onMounted(() => {
  const { id = '' } = route.query
  nodeId.value = id
  loadData()
})
const editSubmit = async (data: any, callBack: Function) => {
  const { id, key, name, nodeType = 'BIZ_NODE', parentId, value = null, provideOptions, label } = data
  const res = await assetsManage.editNode({
    id,
    key, // key，只有当节点类型为keyNode时，此值不能为空
    name, // 名称
    nodeType, // 节点类型
    parentId, // 父节点id，顶级节点为0，二级节点为上级节点id，三级节点为上级节点id，以此类推。
    value, // value值，只有当nodeType为valueNode时，此值不能为空。
    provideOptions, // 是否提供可选项，不提供可选项时此KEY_NODE不应该存在VALUE_NODE节点;
    dataType: 'ARRAY', // key对应的数据类型，不能为空(ARRAY：数组，NUMBER：数字，OBJECT：对象，STRING：字符串)
    label // 标签
  })
  ElMessage.success(res?.message)
  await loadData()
  callBack && callBack()
}
const sendDataToParCom = (data: any, callBack: Function) => {
  editSubmit(data, callBack)
}
const sendDataToParComLabel = async (data: any) => {
  try {
    const res = await assetsManage.addLabels({ id: labelDialogData.id, labels: data?.label })
    console.log(res)
    if (res.code === '000000') {
      state.listData.forEach((item: any) => {
        if (item?.id === data?.id) {
          item.label = data?.label || []
        }
      })
    }
  } catch (e) {
    console.log(e)
  }
}
const handleEdit = async (row: any) => {
  console.log(row)
  dialogVisible.value = true
  dialogData.value = row
}

const labelDialogData = {
  id: ''
}
const handleAddLabels = (row: any) => {
  labelDialog.value = true
  labelDialogData.id = row.id
}
const handleRemove = async (row: any, index: number) => {
  console.log(index, row)
  const res = await assetsManage.deleteNode({ id: row.id })
  if (res.code === '000000') {
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    loadData()
  }
}

</script>

<style scoped lang="less">
.list-header {
  display: flex;
  align-items: center;
  .back-btn {
    cursor: pointer;
  }
}
.list-box{
  background: #fff;
  border-radius: 8px;
  padding-left:16px;
  padding-right:16px;
}
.list-content{
  position:relative;
  .btn_wrap{
    width:100%;
    position: relative;
    height:38px;
  }
  .search_wrap{
    height:30px;
  }
}
:deep(.el-tabs--top .el-tabs__item.is-top) {
  width: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
}
:deep(.el-tabs__active-bar){
  height: 2px;
}
:deep(.el-breadcrumb){
  font-weight: 500;
  font-size: 22px;
  color: black;
  margin: 24px 0;
}
.removeButton{
  color: red;
  cursor: pointer;
}
.del-button{
  span{
    color: red;
  }
}
.manage{
  display: flex;
  flex-direction: column;
  span{
    color: var(--el-color-primary);
    margin-top: 4px;
    cursor: pointer;
  }
}
.action-btn {
  margin-right: 10px;
}
:deep(.el-table--fit){
  max-height: 600px;
  overflow: scroll;
}
// :deep(.el-tabs__content){
//   border: solid 1px #ccc;
// }
</style>
